using System;
using System.Configuration;
using System.IO;
using Abp.Dependency;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Batman.Cms.Core.Utils
{
    public class AppSettingsUtil : ITransientDependency
    {
        private IConfigurationRoot _configuration;

        private readonly IConfigurationBuilder _configurationBuilder;

        private AppSettingsUtil(string basepath, string jsonfilename = "appsettings.json")
        {
            _configurationBuilder = new ConfigurationBuilder();
            _configuration = _configurationBuilder.SetBasePath(basepath)
                .AddJsonFile(cfg =>
                {
                    cfg.Path = jsonfilename;
                    cfg.ReloadOnChange = true;
                    cfg.Optional = false;
                })
                //Build方法的调用要在AddJsonFile之后，否则生成的IConfigurationRoot实例的
                //Providers属性不包含任何元素而导致无法读取文件中的信息
                .Build();

            //遍历配置文件中的所有元素
//            foreach (var keyValuePair in _configuration.AsEnumerable())
//            {
//                Console.WriteLine($"{keyValuePair.Key} - {keyValuePair.Value}");
//            }
        }

        /// <summary>
        /// 获取值
        /// </summary>
        /// <param name="aPath">扁平化的路径，例如:SenparcWeixinSetting:WeixinAppId</param>
        /// <returns></returns>
        public string Get(string aPath)
        {
            return _configuration[aPath].ToString();
        }

        /// <summary>
        /// 把appsettingh整个文件映射到对象中
        /// </summary>
        /// <param name="appsettings"></param>
        /// <typeparam name="T"></typeparam>
        public void Bind<T>(out T appsettings) where T : class, new()
        {
            appsettings = new T();
            _configuration.Bind(appsettings);
        }

        #region 单例据柄

        private static AppSettingsUtil _defaultInstance { get; set; }

        /// <summary>
        /// 系统配置的实例
        /// </summary>
        public static AppSettingsUtil DefaultInstance
        {
            get
            {
                if (_defaultInstance == null)
                    _defaultInstance = new AppSettingsUtil(Directory.GetCurrentDirectory());

                return _defaultInstance;
            }
        }

        #endregion
    }
}